package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.apache.ibatis.executor.BatchExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {


    //todo 根据SpuId查询SKU集合
    @Override
    public List<SkuDTO> querySkusBySpuId(Long id) {


        List<Sku> skuList = this.query().eq("spu_id", id).list();

        List<SkuDTO> skuDTOS = SkuDTO.convertEntityList(skuList);

        return skuDTOS;
    }

    //根据skuids 查询对应得sku集合
    @Override
    public List<SkuDTO> querySkuBySpuIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)){
            throw new LyException(400,"查询ids不能为空");
        }
            List<Sku> skuList = this.listByIds(ids);

        return SkuDTO.convertEntityList(skuList);
    }



    private static final String MINUS_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.minusSku";

    @Override
    @Transactional
    public void minusSku(Map<Long, Integer> cartsMap) {


     /*   for (Map.Entry<Long, Integer> entry : cartsMap.entrySet()) {//这样多线程会有问题 ,两个人同时进来 买同一个商品
            //获取商品id
            Long skuId = entry.getKey();
            //获取商品id 对应的数量
            Integer num = entry.getValue();

            //根据id 获取sku
            Sku sku = getById(skuId);

            //库存减去下单数量
            sku.setStock(sku.getStock()-num);
            //销量+下单数量
            sku.setSold(sku.getSold()+num);
            //进行修改数据
            this.updateById(sku);

        }
*/

    /*    //直接修改 update tb_sku set stock =stock-num, sold=sold+num where id = xxx
        for (Map.Entry<Long, Integer> entry : cartsMap.entrySet()) {
           //根据数据id 和数量 进行修改  此时需要对数据库表中库存字段进行 无符号约束 这样不会为负
            baseMapper.minusSku(entry.getKey(),entry.getValue());

        }*/

         //todo 批量执行  使用自定义的sql语句 这样好像可以解决多线程问题
        executeBatch(sqlSession -> {
            for (Map.Entry<Long, Integer> entry : cartsMap.entrySet()) {
                // 准备参数
                Map<String,Object> param = new HashMap<>();
                param.put("id", entry.getKey());
                param.put("num", entry.getValue());
                // 编译statement，namespace.statementId
                sqlSession.update(MINUS_STOCK_STATEMENT, param);//全限定名
            }
            // 刷新
            sqlSession.flushStatements();
        });





    }
}
